<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>demo</title>
</head>
<body>
  <video id="video" width="320" height="480" controls></video>
  <div>
    <button id="camera">打开/切换摄像头</button>
    <button id="stop">关闭摄像头</button>
    <button id="capture">拍照</button>
    
  </div>
  <canvas id="canvas" width="320" height="480"></canvas>
  <script>
    //访问用户媒体设备的兼容方法
    function getUserMedia(constraints, success, error) {
      if (navigator.mediaDevices.getUserMedia) {
        //最新的标准API
        navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
      } else if (navigator.webkitGetUserMedia) {
        //webkit核心浏览器
        navigator.webkitGetUserMedia(constraints, success, error)
      } else if (navigator.mozGetUserMedia) {
        //firfox浏览器
        navigator.mozGetUserMedia(constraints, success, error);
      } else if (navigator.getUserMedia) {
        //旧版API
        navigator.getUserMedia(constraints, success, error);
      }
    }
 
    let video = document.getElementById('video');
    let canvas = document.getElementById('canvas');
    let context = canvas.getContext('2d');
 
    function success(stream) {
      //兼容webkit核心浏览器
      let CompatibleURL = window.URL || window.webkitURL;
      //将视频流设置为video元素的源
      console.log(stream);
 
      //video.src = CompatibleURL.createObjectURL(stream);
      video.srcObject = stream;
      video.play();
    }
 
    function error(error) {
      console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
    }
    
    function close() { //关闭摄像头数据流
      if (video.srcObject) {
        try {
          var tracks = video.srcObject.getTracks();
          for (var track of tracks) {
            track.stop();
          }
        } catch (e) {
          alert(e);
        }
      }
    }
 
    document.getElementById('stop').addEventListener('click', close);
 
    //设备摄像头数据获取
    var device_videos = [];
    var device_videos_index = 0;
    navigator.mediaDevices.enumerateDevices().then(function (devices) {
      devices.forEach(function (dv) {
        var kind = dv.kind;
        if (kind.match(/^video.*/)) {
          device_videos.push(dv.deviceId);
        }
      });
    });
 
    document.getElementById('camera').addEventListener('click', function () {
      if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
        //调用用户媒体设备, 访问摄像头
        close();
        getUserMedia({ video: { width: 320, height: 480, deviceId: device_videos[device_videos_index++%device_videos.length] } }, success, error);
      } else {
        alert('不支持访问用户媒体');
      }
    })
 
    document.getElementById('capture').addEventListener('click', function () {
      context.drawImage(video, 0, 0, 320, 480);
    })
 
  </script>
</body>
</html>
